package week2;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

import static io.netty.handler.codec.http.HttpHeaderNames.*;

/**
 * @author lv
 * @date 2021/4/3 14:34
 */
public class HttpOutboundHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
         ctx.flush();
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            FullHttpRequest fullHttpRequest = (FullHttpRequest)msg;
            //1.（必做）整合你上次作业的 httpclient/okhttp；
            httpclientUtil(fullHttpRequest,ctx);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
    private void httpclientUtil(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String uri = fullHttpRequest.uri();
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8088"+uri);
        //3.（必做）实现过滤器。
        httpGet.setHeader("token", fullHttpRequest.headers().get("token"));
        CloseableHttpResponse response = null;
        FullHttpResponse res = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());

            HttpResponseStatus httpResponseStatus = new HttpResponseStatus(response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase());
            if(entity != null){
                System.out.println("响应内容长度为:" + entity.getContentLength());
                String body = EntityUtils.toString(entity);
                System.out.println("响应内容为:" + body);

                res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus , Unpooled.wrappedBuffer(body.getBytes()));
                res.headers().set("Content-Type","text/html;charset=utf-8");
                res.headers().setInt("Content-length",res.content().readableBytes());
            }

        } catch (IOException e) {
            e.printStackTrace();
            res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.NO_CONTENT);
        }finally {
            if(fullHttpRequest != null){
                if(!HttpUtil.isKeepAlive(fullHttpRequest)){
                    ctx.write(res).addListener(ChannelFutureListener.CLOSE);
                }else{
                    res.headers().set(CONNECTION,KEEP_ALIVE);
                    ctx.write(res);
                }
            }
        }
    }
}
